import search from './search/index.vue'
import { listUser, listDeptUser } from '@/api/system/user.js'
import { item } from '../../../api/repair/repair'
import { staticUrl } from '@/config.js'

export default {
  name: 'treeComponent',
  data() {
    return {
      staticUrl,
      isre: false,
      deptListData: Object.freeze(this.treeNone),
      newNum: 0,
      oldNum: 0,
      catchTreeNone: [...this.treeNone],
      tree_stack: [1],
      searchResult: [],
      deptCheckList: [],
      scrollLeft: 999,
      nodePathArray: [],
      userListData: [], // 部门下用户数据
      userCheckList: [], // 已选中用户数据
      selectedInfoPopup: false // 已选择人员信息
    }
  },
  inject: {
    isAll: { value: 'isAll', default: null }
  },
  watch: {
    checkList: {
      handler(newVal) {
        if (!(newVal instanceof Array)) {
          this.userCheckList = []
        } else {
          this.userCheckList = newVal
        }
      },
      deep: true,
      immediate: true
    }
  },
  components: {
    search
  },
  computed: {
    allDeptUserCount() {
      let sum = 0
      this.deptListData?.map((item) => {
        sum += item.staffCount
      })
      return sum
    },
    selectAllStatus() {
      let total = 0
      this.userListData?.map((i) => {
        if (this.userCheckList.some((j) => j.userId == i.userId)) {
          total++
        }
      })
      this.deptListData?.map((i) => {
        if (this.deptCheckList.some((j) => j.deptId == i.deptId)) {
          total += i.staffCount
        }
      })
      console.log('this.userListData', this.userListData)
      return this.userListData.length + this.allDeptUserCount === total && total > 0
    },
    // 选中的人数
    getUserNum() {
      let sum = 0
      sum += this.userCheckList.length
      this.deptCheckList.map((item) => {
        sum += item.staffCount
      })
      return sum
    },
    // 用户是否选中
    isUserSelect() {
      return (item) => {
        const userCheckList = this.userCheckList
        if (userCheckList.length == 0) {
          return false
        }
        const i =
          userCheckList.findIndex((e) => {
            return item.userId == e.userId
          }) > -1
        return i
      }
    },
    // 部门是否选中
    isSelect() {
      return (item) => {
        const checkList = this.deptCheckList
        const i =
          checkList.findIndex((e) => {
            return item[this.keyCode] == e[this.keyCode]
          }) > -1
        return i
      }
    },
    radioSelect() {
      const list = this.deptCheckList
      return (item) => {
        return list.length > 0 && item[this.keyCode] == list[0][this.keyCode]
      }
    },
    keyCode() {
      return this.keyValue
    },
    isActive() {
      return (index) => {
        return index === this.tree_stack.length - 1
      }
    }
  },
  created() {
    this.Init()
  },
  methods: {
    selectAllHandle() {
      if (this.selectAllStatus) {
        // 反选
        this.userCheckList = this.deleteArr(this.userListData, this.userCheckList, 'userId')
        this.deptCheckList = this.deleteArr(this.deptListData, this.deptCheckList, 'deptId')
      } else {
        // 全选
        this.userCheckList = this.conbineArr(this.userListData, this.userCheckList, 'userId')
        this.deptCheckList = this.conbineArr(this.deptListData, this.deptCheckList, 'deptId')
      }
    },
    // 数组合并去重 （全选）
    conbineArr(arr1, arr2, key) {
      let arrs = [...(arr1 || []), ...(arr2 || [])]
      //根据key去重
      let map = new Map()
      for (let item of arrs) {
        if (item.userCount <= 0) {
          break
        }
        if (!map.has(item[key])) {
          map.set(item[key], item)
        }
      }
      return [...map.values()]
    },
    // 数组合并删除 (反选)
    deleteArr(arr1, arr2, key) {
      let arrs = [...arr1, ...arr2]
      //根据key去重
      let map = new Map()
      for (let item of arrs) {
        if (map.has(item[key])) {
          map.delete(item[key])
        }
      }
      return [...map.values()]
    },
    // 初始化
    Init() {
      // if (!this.multiple) {
      //   this.deptListData = []
      //   this.getDeptUser(this.deptId || 1)
      // }
    },
    // 部门点击处理
    handleDeptClick(item, index) {
      if (item.userCount <= 0) {
        uni.showToast({
          title: '该部门下暂无人员',
          icon: 'none'
        })
        return
      }
      if (this.deptCheckList.some((j) => j.deptId == item.deptId) && index > -1) {
        return
      }
      let children = item[this.treeProp.children]
      if (index > -1) {
        this.toChildren(item)
        this.getDeptUser(item.deptId)
      } else if (this.multiple) {
        this.deptMultipleClick(item, index)
      } else {
        this.deptRadioClick(item, index)
      }
    },
    // 部门单选
    deptRadioClick(item, index) {
      const path = this.getPath()
      this.$set(this, 'deptCheckList', [{ ...item }])
    },
    // 部门多选
    deptMultipleClick(item, index) {
      let findIdex = this.deptCheckList.findIndex((e) => item.deptId == e.deptId)
      if (findIdex > -1) {
        this.deptCheckList.splice(findIdex, 1)
      } else {
        this.deptCheckList.push(item)
      }
    },
    // 人员点击处理
    handleUserClick(item, index) {
      if (this.multiple) {
        this.userMultipleClick(item, index)
      } else {
        this.userRadioClick(item, index)
      }
    },
    // 人员单选
    userRadioClick(item, index) {
      const path = this.getPath()
      this.$set(this, 'userCheckList', [{ ...item, path }])
    },
    // 人员多选
    userMultipleClick(item, index) {
      if (!this.multiple) return
      let findIdex = this.userCheckList.findIndex((e) => item.userId == e.userId)
      if (findIdex > -1) {
        this.userCheckList.splice(findIdex, 1)
      } else {
        this.userCheckList.push(item)
      }
    },
    // 获取部门用户
    async getDeptUser(deptId) {
      if (!deptId) {
        this.userListData = []
        return
      }
      const data = {
        deptId: deptId
      }
      let res
      if (this.multiple) {
        res = await listDeptUser(data)
      } else {
        res = await listUser(data)
      }
      let arr = []
      for (var i = 0; i < res.data.length; i++) {
        res.data[i].user = true
        res.data[i].userId = res.data[i].staffId
        res.data[i].name = res.data[i].staffName
        if (this.excludeIds.indexOf(res.data[i].userId) == -1) {
          arr.push(res.data[i])
        }
      }
      this.userListData.splice(0, this.userListData.length, ...arr)
    },
    // 获取路径
    getPath() {
      const path = [...this.tree_stack].map((e) => {
        const item = Object.assign({}, e)
        delete item[this.treeProp.children]
        return item
      })
      return path.slice(1, path.length) || []
    },

    // 取消下一级的选中
    getIdBydelete(arr) {
      arr.forEach((e) => {
        if (e.user) {
          for (var i = 0; i < this.deptCheckList.length; i++) {
            if (e[this.keyCode] == this.deptCheckList[i][this.keyCode]) {
              this.deptCheckList.splice(i, 1)
              break
            }
          }
        } else {
          this.getIdBydelete(e.children)
        }
      })
    },

    // 关联下一级,选中
    chooseChild(arr, path) {
      let that = this
      const oldPath = [...path]
      for (var i = 0, len = arr.length; i < len; i++) {
        let item = arr[i]
        if (item.user) {
          that.deptCheckList.push({ ...item, path: oldPath })
        } else {
          const newItem = { ...item }
          delete newItem[that.treeProp.children]
          const newPath = [...oldPath, newItem]
          that.chooseChild(item.children, newPath)
        }
      }
    },
    //到下一级
    toChildren(item) {
      if (item.user) return
      uni.showLoading({
        title: '加载中'
      })
      let children = this.treeProp.children
      this.deptListData = item[children] || []
      this.tree_stack.push(item)
      this.$nextTick(() => {
        uni.hideLoading()
        this.scrollLeft += 200
      })
    },
    //搜索
    async confirmSearch(val) {
      let data = {
        keyword: val
      }
      if (!this.multiple && this.deptId) {
        data.deptId = this.deptId
      }
      let res
      if (this.multiple) {
        res = await listDeptUser(data)
      } else {
        res = await listUser(data)
      }
      this.deptListData = []
      this.isre = true
      this.tree_stack.splice(1, 1000)
      this.userListData = res.rows ?? res.data ?? []
    },

    searchUser(data, keyword) {
      this.userListData = []
      for (var i = 0, len = data.length; i < len; i++) {
        if (data[i]['name'].indexOf(keyword) >= 0) {
          this.userListData.push(data[i])
        }
      }
    },

    //返回其它层
    backTree(item, index) {
      console.log(item, index)
      let that = this,
        tree_stack = that.tree_stack,
        max = 300
      if (index === -1) {
        that.deptListData = that.catchTreeNone
        that.tree_stack.splice(1, max)
        that.isre = false
        that.$refs.sea.clears()
      } else if (index === -2) {
        //搜索
        that.deptListData = that.searchResult
        that.tree_stack.splice(1, max)
      } else {
        if (tree_stack.length - index > 2) {
          that.tree_stack.splice(index + 1, max)
        } else if (index !== tree_stack.length - 1) {
          that.tree_stack.splice(tree_stack.length - 1, 1)
        }
        that.deptListData = item[that.treeProp.children]
      }
      this.getDeptUser(this.tree_stack[this.tree_stack.length - 1].deptId)
      this.$forceUpdate()
    },
    async backConfirm() {
      if (this.deptCheckList.length > 0) {
        let arr = []
        for (var i = 0; i < this.deptCheckList.length; i++) {
          const data = {
            deptId: this.deptCheckList[i].deptId
          }
          const res = await listUser(data)
          res.data.forEach((item) => {
            item.userId = item.staffId
            item.name = item.staffName
          })
          arr = this.conbineArr(res.data, arr, 'userId')
        }
        arr = this.conbineArr(arr, this.userCheckList, 'userId')
        this.$emit('sendValue', arr)
      } else {
        this.$emit('sendValue', this.userCheckList)
      }
    }
  },
  props: {
    checkList: {
      type: [Number, String, Array]
    },
    // 排除的用户ID
    excludeIds: {
      type: Array,
      default: () => {
        return []
      }
    },
    treeNone: {
      type: Array,
      default: () => {
        return []
      }
    },
    //是否开启选中
    isCheck: {
      type: Boolean,
      default: () => {
        return false
      }
    },
    parentList: {
      type: Array,
      default: () => []
    },
    searchIf: {
      type: Boolean,
      default: () => true
    },
    keyValue: {
      type: String,
      default: 'id'
    },
    treeProp: {
      type: Object,
      default: () => {
        return {
          label: 'name',
          children: 'children',
          checkStrictly: false //不关联
        }
      }
    },
    multiple: {
      type: Boolean,
      default: () => false
    },
    deptId: {
      type: [String, Number],
      default: ''
    }
  }
}
